package com.happyghost.middleware.server.service.redis;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.happyghost.middleware.model.entity.Item;
import com.happyghost.middleware.model.mapper.ItemMapper;
import org.assertj.core.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Service
public class CachePassService {
    private Logger logger = LoggerFactory.getLogger(CachePassService.class);

    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    private static final String keyPrefix = "item:";


    public Item getItemInfo(String itemCode) throws IOException {
        Item item = null;
        final String key = keyPrefix + itemCode;
        ValueOperations valueOperations = redisTemplate.opsForValue();

        if (redisTemplate.hasKey(key)) {
            Object res = valueOperations.get(key);
            if (res != null && !Strings.isNullOrEmpty(res.toString())) {
                item = objectMapper.readValue(res.toString(), Item.class);
            }
        }else{
            item = itemMapper.selectByCode(itemCode);

            if (item != null) {
                valueOperations.set(key,objectMapper.writeValueAsString(item));
            }else{
                valueOperations.set(key,"",30L, TimeUnit.MINUTES);
            }
        }

        return item;
    }











}
